package com.zjc.mall.gateway.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

/**
 * @Author: JinChen Zhu
 * @CreateTime: 2024-07-23  20:13
 */
@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter() {
        // 创建一个基于URL的CORS配置源
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        // 创建一个CORS配置对象
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 允许哪些Header跨域
        corsConfiguration.addAllowedHeader("*");
        // 允许哪些请求方法跨域
        corsConfiguration.addAllowedMethod("*");
        // 允许哪些Origin跨域
//        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedOriginPattern("*"); // springboot 2.43版本之后
        // 是否允许携带cookie
        corsConfiguration.setAllowCredentials(true);

        // 将CORS配置注册到配置源中，并应用到所有路径
        source.registerCorsConfiguration("/**", corsConfiguration);

        // 创建一个CorsWebFilter对象并返回
        return new CorsWebFilter(source);
    }
}
